package com.sinvo.oa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sinvo.oa.entity.model.process.Process;
import com.sinvo.oa.entity.model.process.ProcessType;
import com.sinvo.oa.exception.CustomException;
import com.sinvo.oa.mapper.ProcessTypeMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinvo.oa.result.ResultCode;
import com.sinvo.oa.service.ProcessTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description ProcessTypeService实现类
 */
@Service
public class ProcessTypeServiceImpl extends ServiceImpl<ProcessTypeMapper, ProcessType> implements ProcessTypeService {

    @Autowired
    private ProcessTypeMapper processTypeMapper;

    @Override
    public void saveType(ProcessType processType) {
        //封装条件 name唯一
        LambdaQueryWrapper<ProcessType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProcessType::getName,processType.getName());
        int count = this.count(queryWrapper);
        if (count > 0){
            throw new CustomException(ResultCode.DATA_ERROR.getCode(),"类型名称重复");
        }
        boolean success = this.save(processType);
        if (!success) {
            throw new CustomException(ResultCode.SERVICE_ERROR.getCode(), "新增失败，请重试");
        }
    }

    @Override
    public void updateType(ProcessType processType) {
        //封装条件 name唯一
        LambdaQueryWrapper<ProcessType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProcessType::getName,processType.getName());
        ProcessType one = this.getOne(queryWrapper);
        if (one != null && one.getId() != processType.getId()){
            throw new CustomException(ResultCode.DATA_ERROR.getCode(),"类型名称重复");
        }
        boolean success = this.updateById(processType);
        if (!success) {
            throw new CustomException(ResultCode.SERVICE_ERROR.getCode(), "更新失败，请重试");
        }
    }

    @Override
    public List<ProcessType> findProcessType() {
        //查询所有审批分类 id->name
        List<ProcessType> typeList = processTypeMapper.queryAllWithTemplates();
        return typeList;
    }
}
